package it.agm.fanta.activity;

import it.agm.activity.dialog.GenericDialog;
import it.agm.fanta.FantaserviceApp;
import it.agm.fanta.R;
import it.agm.fanta.asynctask.UserLoginTask;
import it.agm.fanta.asynctask.jersey.patch.NetworkHandler;
import it.agm.fanta.asynctask.util.SyncUtility;
import it.agm.fanta.constants.Constants;
import it.agm.fanta.model.Request;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
//import android.widget.CheckBox;


import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

/**
 * Activity Che visualizza la pagina di login o effettua direttamente la login se l'utente ha impostato 
 * il check rimani connesso
 */
public class LoginActivity extends Activity {

	private static final String URL_REGISTRAZIONE = "http://www.fantacalcioservice.it/it/registrati/";


	/**
	 * The default email to populate the email field with.
	 */
//	private static final String EMAIL_REGEX = "[a-zA-Z0-9._-]+@[a-z\\.]+\\.+[a-z]+";
	

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;


	private String digitUsername;
	private String digitPassword;
	private Intent intent;

	private EditText mEmailView;
	private EditText mPasswordView;
	private CheckBox rimaniConnesso;
	private View mLoginFormView;
	private View mLoginStatusView;
//	private View mSplashScreen;
	private TextView mLoginStatusMessageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		intent = new Intent(this, MainActivity.class);
		FantaserviceApp.resetApplicationData();
		FantaserviceApp.setCurrentActivity(this);
		SharedPreferences pref = getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE);   
		String username = pref.getString(Constants.PREF_USERNAME, null);
		String password = pref.getString(Constants.PREF_PASSWORD, null);
		boolean connection = NetworkHandler.checkConnection(FantaserviceApp.getAppContext());
		
			if (connection && username != null && password != null && !"".equals(username) && !"".equals(password)) {
				setContentView(R.layout.splashscreen);
//				mLoginStatusView = null;
//				mSplashScreen = findViewById(R.id.splashScreen);
//				mSplashScreen.setVisibility(View.GONE);
				digitUsername = username;
				digitPassword = password;
				if(SyncUtility.isConnectionPresent(this)){
					showProgress(true);
					attemptLogin();
				}else{
					new GenericDialog(FantaserviceApp.currentActivity(), SyncUtility.ERRORE_DI_CONNESSIONE,"ERROR");
				}	
			}else{
				if(digitUsername == null || "".equals(digitUsername)){
					setContentView(R.layout.activity_login);
					//ADVIEW
					 AdView adView = (AdView) this.findViewById(R.id.adView);
					 AdRequest adRequest = new AdRequest.Builder().build();
					 if(adView != null){
						 adView.loadAd(adRequest);
					 }
					//ADVIEW
					rimaniConnesso =  (CheckBox) findViewById(R.id.checkRimaniConnesso);
		
					// Set up the login form.
					//digitUsername = getIntent().getStringExtra(EXTRA_EMAIL);
					mEmailView = (EditText) findViewById(R.id.email);
					mEmailView.setText(digitUsername);
		
					mPasswordView = (EditText) findViewById(R.id.password);
					mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
								@Override
								public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
									if (id == R.id.login || id == EditorInfo.IME_NULL) {
										attemptLogin();
										return true;
									}
									return false;
								}
							});
		
					mLoginFormView = findViewById(R.id.login_form);
					mLoginStatusView = findViewById(R.id.login_status);
					
					mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
		
					findViewById(R.id.sign_in_button).setOnClickListener(
							new View.OnClickListener() {
								@Override
								public void onClick(View view) {
								
									
										//rimaniConnesso =  (CheckBox) findViewById(R.id.checkRimaniConnesso);
										InputMethodManager inputManager = (InputMethodManager)
				                                  getSystemService(Context.INPUT_METHOD_SERVICE); 
			
										inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
				                                     InputMethodManager.HIDE_NOT_ALWAYS);
										attemptLogin();
								}
							});
					findViewById(R.id.registrati).setOnClickListener(
							new View.OnClickListener() {
								@Override
								public void onClick(View view) {
									
									Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL_REGISTRAZIONE));
									startActivity(browserIntent);
								}
							});
					}
			}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		//getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		boolean primoTentativo = true;
		if (mAuthTask != null) {
			mAuthTask = null;
			primoTentativo=false;
		}
		boolean cancel = false;
		View focusView = null;
		boolean mailControl = true;
		
		// Reset errors.
//		if(mEmailView != null){
//			mEmailView.setError(null);
//			mailControl = mEmailView.getText().toString().matches(EMAIL_REGEX);
//		}
		if(mPasswordView != null){
			mPasswordView.setError(null);
		}
		if((digitUsername == null || "".equals(digitUsername) || !mailControl) || !primoTentativo){
			// Store values at the time of the login attempt.
			digitUsername = mEmailView.getText().toString();
			digitPassword = mPasswordView.getText().toString();
			// Check for a valid password.
			if (TextUtils.isEmpty(digitPassword)) {
				mPasswordView.setError(getString(R.string.error_field_required));
				focusView = mPasswordView;
				cancel = true;
			}

			// Check for a valid email address.
			if (TextUtils.isEmpty(digitUsername)) {
				mEmailView.setError(getString(R.string.error_field_required));
				focusView = mEmailView;
				cancel = true;
			}else if(!mailControl){
				mEmailView.setError(getString(R.string.error_email_required));
				focusView = mEmailView;
				cancel = true;
			}
			if (cancel) {
				focusView.requestFocus();
			}else{
//				if(NetworkHandler.checkConnection(App.getAppContext())){
				if(SyncUtility.isConnectionPresent(this)){
					mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
					showProgress(true);
				}	
//				}else{
//					new GenericDialog(this, "Errore di connessione","ERROR");
//					showProgress(false);
//				}	
				
			}
		}

		if (!cancel) {
				
			FantaserviceApp.request = new Request();
			FantaserviceApp.request.setUsername(digitUsername);
			FantaserviceApp.request.setPassword(digitPassword);
//			
			if(SyncUtility.isConnectionPresent(this)){
				mAuthTask = new UserLoginTask(this.getApplicationContext(),this,intent,(rimaniConnesso != null && rimaniConnesso.isChecked()));
				
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
					mAuthTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
				}else{
					mAuthTask.execute((Void[])null);
				}
			}else{
				new GenericDialog(FantaserviceApp.currentActivity(), SyncUtility.ERRORE_DI_CONNESSIONE,"ERROR");
			}
			
//			mAuthTask.execute((Void) null);

		}

	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	public void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if(mLoginStatusView != null){
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
				int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
				
					mLoginStatusView.setVisibility(View.VISIBLE);
					mLoginStatusView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
								@Override
								public void onAnimationEnd(Animator animation) {
									mLoginStatusView.setVisibility(show ? View.VISIBLE
											: View.GONE);
								}
							});
		
					mLoginFormView.setVisibility(View.VISIBLE);
					mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
								@Override
								public void onAnimationEnd(Animator animation) {
									mLoginFormView.setVisibility(show ? View.GONE
											: View.VISIBLE);
								}
							});
				} else {
					// The ViewPropertyAnimator APIs are not available, so simply show
					// and hide the relevant UI components.
					mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
					mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
				}
		}

	}
}
